package cn.lena.idle.adapter;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.lena.idle.R;
import cn.lena.idle.pojo.Goods;

public class MyCollectionAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater layoutInflater;

    HashMap<Integer,View> location = new HashMap<>();
    private List<Goods> lists=new ArrayList<>();

    public MyCollectionAdapter(Context context){
        this.context=context;
        layoutInflater=LayoutInflater.from(context);
    }

    public void setData(List<Goods> lists){
        this.lists=lists;
        notifyDataSetChanged();
    }


    static class ViewHolder{

        public ImageView picture;
        public TextView title,describe,phone,address,publishTime,price;

        public ViewHolder(View itemView,Goods goods){

            // 获取控件
            picture=itemView.findViewById(R.id.good_picture);
            title=itemView.findViewById(R.id.good_title);
            describe=itemView.findViewById(R.id.good_describe);
            phone=itemView.findViewById(R.id.user_phone);
            address=itemView.findViewById(R.id.good_address);
            publishTime=itemView.findViewById(R.id.good_time);
            price=itemView.findViewById(R.id.good_price);

            // 给控件赋值
            byte[] goodsPicture=goods.getPicture();
            picture.setImageBitmap(BitmapFactory.decodeByteArray(goodsPicture,0,goodsPicture.length));
            title.setText(goods.getGoodsName());
            describe.setText(goods.getDescribe());
            phone.setText(goods.getPhone());
            address.setText(goods.getAddress());
            publishTime.setText(goods.getPublishTime());
            price.setText(goods.getPrice());

        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if(location.get(position) == null) {
            convertView = layoutInflater.inflate(R.layout.item_mycollection,null);
            Goods goods = (Goods)getItem(position);
            holder = new ViewHolder(convertView,goods);
            location.put(position,convertView);
            convertView.setTag(holder);
        }else{
            convertView = location.get(position);
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }

    /**
     * TODO:数据长度
     * @return
     */
    @Override
    public int getCount() {
        return lists.size();
    }

    @Override
    public Object getItem(int position) {
        return lists.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


}
